module Dior
  class Component
    attr_reader :name, :deps, :raw_content

    def initialize(name, dependencies = [], global: false, &block)
      @name = normalize_name(name)
      @global = global
      @deps = [dependencies].flatten(1)
      @raw_content = block ? instance_eval(&block) : ''
    end

    def di(dep)
      normalize_name(dep).tap{|name| @deps << name}
    end

    def global?
      @global
    end

    def wrapped_content
      <<-JAVASCRIPT
      (function () {
        #{@raw_content}
      })();
      JAVASCRIPT
    end

    def content
      @global ? raw_content : wrapped_content
    end

    private

    def normalize_name(name)
      name.to_s.tr('.', '$')
    end
  end
end